'''
filename: dataFormat
author: yinwenlu
datetime: 2019/10/1 15:31
software: PyCharm
'''
import datetime



def overDataFormat(data,type):
    '''

    :param data:
    :param type:
    :return:
    '''
    exposure={"myShop":[],"otherTopShop":[],"percent":[]}
    visitRate={"myShop":[],"otherTopShop":[],"percent":[]}
    orderRate = {"myShop": [], "otherTopShop": [],"percent":[]}
    if type ==1:
        data=data.get("flowChartsInfoList",[])
        for everyDay in data:
            exposure['myShop'].append(everyDay['exposureNum'])
            exposure['otherTopShop'].append(everyDay['exposureNumTop'])
            exposure['percent'].append(everyDay['exposureNum'] / everyDay['exposureNumTop'])
            visitRate['myShop'].append(everyDay['visitRate'])
            visitRate['otherTopShop'].append(everyDay['visitRateTop'])
            visitRate['percent'].append(everyDay['visitRate'] / everyDay['visitRateTop'])
            orderRate['myShop'].append(everyDay['orderRate'])
            orderRate['otherTopShop'].append(everyDay['orderRateTop'])
            orderRate['percent'].append(everyDay['orderRate'] / everyDay['orderRateTop'])
    else:
        eleFlow=data.get("eleFlow",{})
        eleFlowTop=data.get("eleFlowTop",{})
        exposureMyShop=eleFlow.get("exposureDist",{}).get("itemValue",{})
        keyStamp=sorted(exposureMyShop)
        exposuretOherTopShop=eleFlowTop.get("exposureDist",{}).get("compareValue")
        visitRateMyShop=eleFlow.get("visitConvRateDist",{}).get("itemValue",{})
        visitRateOtherTopShop=eleFlowTop.get("visitConvRateDist",{}).get("compareValue",{})
        orderRateMyShop=eleFlow.get("buyerConvRateDist",{}).get("itemValue",{})
        orderRateOtherTopShop=eleFlowTop.get("buyerConvRateDist",{}).get("compareValue",{})
        for key in keyStamp:
            exposure['myShop'].append(exposureMyShop[key])
            exposure['otherTopShop'].append(exposuretOherTopShop[key])
            visitRate['myShop'].append(visitRateMyShop[key])
            visitRate['otherTopShop'].append(visitRateOtherTopShop[key])
            orderRate['myShop'].append(orderRateMyShop[key])
            orderRate['otherTopShop'].append(orderRateOtherTopShop[key])
            exposure['percent'].append(exposureMyShop[key] / exposuretOherTopShop[key])
            visitRate['percent'].append(visitRateMyShop[key] / visitRateOtherTopShop[key])
            orderRate['percent'].append(orderRateMyShop[key]/ orderRateOtherTopShop[key])
    result={}
    time=[]
    today=datetime.datetime.now().date()
    for i in range(1,8):
        time.append((today+datetime.timedelta(days=i-8)).strftime("%Y-%m-%d"))
    result={"time":time,"exposure":exposure,"visitRate":visitRate,"orderRate":orderRate}
    return result
def updYseOrderInfo(account,infoList,today,ct):
    '''
    添加最新的昨日订单信息
    :param account:
    :param infoList:
    :param ct:
    :return:
    '''
    try:
        yesOrderInfo=YesOrderInfo()
        yesOrderInfo.account=account
        yesOrderInfo.InfoList=str(infoList)
        yesOrderInfo.day=today
        yesOrderInfo.updatetime=ct
        session=Session()
        nowOrderInfo=session.query(YesOrderInfo).filter(YesOrderInfo.account==account,YesOrderInfo.day==today).first()
        if nowOrderInfo:
            nowOrderInfo.InfoList = str(infoList)
            nowOrderInfo.updatetime = ct
            session.commit()
            session.close()
        else:
            session.add(yesOrderInfo)
            session.commit()
            session.close()
    except:
        logger.warning(traceback.format_exc())
        return dict(code=500, message="fail", data=traceback.format_exc())
def getYesOrderList(spideObj,account,mins,type,today=None,ct=None,yesstart=None, yesend=None):
    '''

    :param mt:
    :param type:
    :return:
    '''
    if type==1:
        yestodayNum = spideObj.get_historyOrder()
        yestodayNum.reverse()
        timelst = []
        for order in yestodayNum:
            # 2019-10-01 21:22:09,返回的时间是这样的，只取21:22:09
            timelst.append(order.split(' ')[1])
        dayperiod = {}
        i = 0
        j = 15
        index = 0
        while i < 24:
            while j <= 60:
                if j == 60:
                    j = 0
                    break
                else:
                    t = "%02d:%02d:00" % (i, j)
                    dayperiod[t] = 0
                    while index < len(timelst) and timelst[index] < t:
                        dayperiod[t] = dayperiod[t] + 1
                        index += 1
                    j += 15
            i += 1
        dayperiod["23:59:59"] = 0
        print(dayperiod)

        orderList = []  # 目前orderlist是96个
        for key, value in dayperiod.items():
            orderList.append(value)

        periodOrderList = []
        index = 0
        if mins == 30:
            # 将俩个俩个相加，变成48个
            while index <= 94:
                periodOrderList.append(orderList[index] + orderList[index + 1])
                index += 2
        elif mins == 60:
            while index <= 92:
                periodOrderList.append(
                    orderList[index] + orderList[index + 1] + orderList[index + 2] + orderList[index + 3])
                index += 4
        elif mins == 15:
            periodOrderList = orderList[:]
        print(periodOrderList, "len:", len(periodOrderList))
        updYseOrderInfo(account, periodOrderList, today, ct)
        return True
    else:
        yestodayNum = spideObj.getAllOrder(yesstart, yesend, 200)
        # print(yestodayNum)

        # 所有下单时间存进列表
        timelst = []
        for order in yestodayNum:
            # 2019-10-01T21:22:09,返回的时间是这样的，只取21:22:09
            timelst.append(order.get("activeTime").split('T')[1])
        timelst.reverse()
        dayperiod = {}
        i = 0
        j = 15
        index = 0
        while i < 24:
            while j <= 60:
                if j == 60:
                    j = 0
                    break
                else:
                    t = "%02d:%02d:00" % (i, j)
                    dayperiod[t] = 0
                    while index < len(timelst) and timelst[index] < t:
                        dayperiod[t] = dayperiod[t] + 1
                        index += 1
                    j += 15
            i += 1
        dayperiod["23:59:59"] = 0

        orderList = []  # 目前orderlist是96个
        for key, value in dayperiod.items():
            orderList.append(value)

        periodOrderList = []
        index = 0
        if mins == 30:
            # 将俩个俩个相加，变成48个
            while index <= 94:
                periodOrderList.append(orderList[index] + orderList[index + 1])
                index += 2
        elif mins == 60:
            while index <= 92:
                periodOrderList.append(
                    orderList[index] + orderList[index + 1] + orderList[index + 2] + orderList[index + 3])
                index += 4
        elif mins == 15:
            periodOrderList = orderList[:]
        updYseOrderInfo(account, periodOrderList, today, ct)
        return True
